<template>
  <a-drawer
    title="流程扩展配置"
    :maskClosable="true"
    width=80%
    placement="left"
    :closable="true"
    @close="onClose"
    :visible="ProcessConfigVisiable">
    <a-card :bordered="false" class="card-area">
      <img :src="'data:image/png;base64,'+imageData">
      <a-divider orientation="left">流程配置</a-divider>
      <a-form :form="form" style="width: 1200px">
        <a-row>
          <a-form-item label='流程启动类型' v-bind="formItemLayout">
            <a-radio-group
              v-decorator="['processUsageType',{rules: [{ required: true, message: '流程启动类型必选'}]}]"
              button-style="solid">
              <a-radio-button value="01">
                申请表单
              </a-radio-button>
              <a-radio-button value="02">
                应用程序
              </a-radio-button>
            </a-radio-group>
          </a-form-item>
        </a-row>
        <a-row>
          <a-form-item label='查询表单标题' v-bind="formItemLayout">
            <a-input
              v-decorator="['qryFormTitle',{rules: [{ required: true, message: '表单标题不能为空'}]}]"/>
          </a-form-item>
        </a-row>
        <a-row>
          <a-form-item label='查询表单类型' v-bind="formItemLayout">
            <a-radio-group
              @change='formTypeChange'
              v-decorator="['qryFormType',{rules: [{ required: true, message: '表单类型不能为空'}]}]">
              <a-radio value="0">系统表单</a-radio>
              <!--            自定义表单暂未实现-->
              <a-radio value="1" disabled>自定义表单</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-row>
        <a-row v-if="ConfigData.qryFormType=='1'">
          <a-col :md="{ span: 12, offset: 3 }">
            <a-form-item label='表单路径' v-bind="formItemLayout">
              <a-input
                v-decorator="['qryFormPath',{rules: [{ required: true, message: '表单路径不能为空'}]}]"/>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-button
              style="float:right;">
              预览表单
            </a-button>
          </a-col>
        </a-row>
        <a-row v-if="ConfigData.qryFormType=='0'">
          <a-form-item label='查询表单关联' v-bind="formItemLayout">
            <a-col>
              <a-select
                show-search
                :filter-option="filterOption"
                v-decorator="['qryFormId',{rules: [{ required: true, message: '请选择表单' }]}]">
                <a-select-option v-for="r in formData" :key="r.formId">{{r.formName}}</a-select-option>
              </a-select>
            </a-col>
            <a-col>
              <a @click="viewForm()">预览</a>
              <a @click="editForm()">编辑</a>
              <a @click="addForm()">创建</a>
            </a-col>
          </a-form-item>
        </a-row>
      </a-form>
      <!-- 表格区域 -->
      <a-divider orientation="left">节点配置</a-divider>
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.nodeId"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :scroll="{ x: 900 }">
        <template slot="operation" slot-scope="text, record">
          <a @click="edit(record)" title="编辑">编辑</a>
        </template>
      </a-table>
    </a-card>
    <div class="drawer-bootom-button">
      <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="loading">保存</a-button>
    </div>
    <!-- 修改节点配置 -->
    <node-config
      ref="NodeConfig"
      @close="handleNodeConfigClose"
      @success="handleNodeConfigSuccess"
      :NodeConfigVisiable="NodeConfig.visiable">
    </node-config>
    <view-form
      ref="ViewForm"
      :ViewFormVisiable="ViewForm.visiable"
      @close="handleViewFormClose">
    </view-form>
    <edit-form
      ref="EditForm"
      :formVisiable="EditForm.visiable"
      @success="handleEditFormSuccess"
      @close="handleEditFormClose">
    </edit-form>
    <add-form
      ref="AddForm"
      :formVisiable="AddForm.visiable"
      @success="handleAddFormSuccess"
      @close="handleAddFormClose">
    </add-form>
  </a-drawer>
</template>
<script>
import NodeConfig from './NodeConfig'
import ViewForm from '../form/ViewForm'
import EditForm from '../form/EditForm'
import AddForm from '../form/AddForm'

const formItemLayout = {
  labelCol: {span: 3},
  wrapperCol: {span: 16}
}

const processConfigFieldLists = ['processUsageType', 'qryFormId', 'qryFormPath', 'qryFormTitle', 'qryFormType']

export default {
  name: 'ProcessConfig',
  components: {NodeConfig, ViewForm, EditForm, AddForm},
  props: {
    ProcessConfigVisiable: {
      default: false
    }
  },
  data () {
    return {
      // 默认值
      imageData: null,
      ConfigData: {
        qryFormType: '0'
      },
      formItemLayout,
      formData: [],
      form: this.$form.createForm(this),
      ViewForm: {
        visiable: false
      },
      EditForm: {
        visiable: false
      },
      AddForm: {
        visiable: false
      },
      ProcessData: {},
      NodeConfig: {
        visiable: false
      },
      queryParams: {},
      sortedInfo: null,
      paginationInfo: null,
      dataSource: [],
      selectedRowKeys: [],
      loading: false,
      pagination: {
        pageSizeOptions: ['10', '20', '50'],
        defaultCurrent: 1,
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
      }
    }
  },
  computed: {
    columns () {
      return [
        {
          title: '节点编码',
          dataIndex: 'nodeId'
        }, {
          title: '节点名称',
          dataIndex: 'nodeName'
        }, {
          title: '表单类型',
          dataIndex: 'formType',
          customRender: (text, record, index) => {
            return text === '0' ? '系统表单' : text === '1' ? '自定义表单' : ''
          }
        }, {
          title: '表单标题',
          dataIndex: 'formTitle'
        }, {
          title: '关联用户',
          dataIndex: 'userIds'
        }, {
          title: '关联角色',
          dataIndex: 'roleNames'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: {customRender: 'operation'}
        }]
    }
  },
  methods: {
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          let values = this.form.getFieldsValue(processConfigFieldLists)
          if (typeof values !== 'undefined') {
            Object.keys(values).forEach(_key => { this.ConfigData[_key] = values[_key] })
          }
          this.loading = true
          this.$put('process/design/saveProcessConfig', {
            ...this.ConfigData, modelId: this.ProcessData.id
          }).then((r) => {
            this.reset()
            this.$message.success('保存成功')
            this.$emit('success')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
    handleViewFormClose () {
      this.ViewForm.visiable = false
    },
    handleEditFormClose () {
      this.EditForm.visiable = false
    },
    handleEditFormSuccess () {
      this.EditForm.visiable = false
      this.$message.success('修改成功')
    },
    handleAddFormClose () {
      this.AddForm.visiable = false
    },
    handleAddFormSuccess () {
      this.$get('form').then((r) => {
        this.formData = r.data.rows
        this.$message.success('创建成功')
        this.AddForm.visiable = false
      })
    },
    formTypeChange (e) {
      this.ConfigData.qryFormType = e.target.value
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    viewForm () {
      // 当前选中的表单json
      let formId = this.form.getFieldValue('qryFormId')
      if (formId == null) {
        this.$message.warn('请先选择表单')
        return
      }
      let data = this.formData.find(value => value.formId === formId)
      this.ViewForm.visiable = true
      this.$refs.ViewForm.setFormValues(data)
    },
    editForm () {
      let formId = this.form.getFieldValue('qryFormId')
      if (formId == null) {
        this.$message.warn('请先选择表单')
        return
      }
      let data = this.formData.find(value => value.formId === formId)
      this.EditForm.visiable = true
      this.$refs.EditForm.setFormData(data)
    },
    addForm () {
      let record = {}
      record.formJson = '{"list":[],"config":{"labelWidth":100,"labelPosition":"right","size":"small","customClass":"","ui":"element","layout":"horizontal","labelCol":3}}'
      this.AddForm.visiable = true
      this.$refs.AddForm.setFormData(record)
    },
    edit (record) {
      this.NodeConfig.visiable = true
      record.modelId = this.ProcessData.id
      this.$refs.NodeConfig.setFormValues({...record})
    },
    handleNodeConfigClose () {
      this.NodeConfig.visiable = false
    },
    handleNodeConfigSuccess () {
      this.NodeConfig.visiable = false
      this.$message.success('修改成功')
      this.search()
    },
    search () {
      this.fetch(this.queryParams)
    },
    reset () {
      // 取消选中
      this.selectedRowKeys = []
      // 重置查询参数
      this.queryParams = {}
      this.fetch()
    },
    fetch () {
      // 显示loading
      this.loading = true
      this.$get('process/design/getProcessConfig', {
        id: this.ProcessData.id
      }).then((r) => {
        Object.keys(r.data).forEach((key) => {
          if (processConfigFieldLists.indexOf(key) !== -1) {
            this.form.getFieldDecorator(key)
            let obj = {}
            obj[key] = r.data[key]
            this.form.setFieldsValue(obj)
          }
        })
      })
      this.$get('process/design/getNodes', {
        id: this.ProcessData.id
      }).then((r) => {
        let data = r.data
        const pagination = {...this.pagination}
        pagination.total = data.total
        this.dataSource = data.rows
        this.pagination = pagination
        // 数据加载完毕，关闭loading
        this.loading = false
      })
    },
    setFormValues (value) {
      this.ProcessData = value
    },
    onClose () {
      this.$emit('close')
    }
  },
  watch: {
    ProcessConfigVisiable () {
      if (this.ProcessConfigVisiable) {
        this.$get('form/getAll').then((r) => {
          this.formData = r.data
        })
        this.$get('process/design/getImage', {
          modelId: this.ProcessData.id
        }).then((r) => {
          this.imageData = r.data.image
        })
        this.fetch()
      }
    }
  }
}
</script>
